package bank;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SaveMoney extends JPanel implements ActionListener {
    private Atm frame;
    private Icon btnOff = Util.getIcon("/images/buttonOff.jpg");
    private Icon btnSure = Util.getIcon("/images/buttonSure.jpg");
    private JButton imageBtn1 = new JButton(btnOff);
    private JButton imageBtn2 = new JButton(btnSure);
    private JTextField saveText = new JTextField();

    public SaveMoney(Atm frame) {
        this.frame = frame;
        this.setLayout(null);
        this.setOpaque(false);
        JLabel save = new JLabel("存钱");
        save.setBounds(50, 50, 100, 50);
        this.add(save);


        JLabel acc = new JLabel("请输入存款金额:");
        acc.setFont(new Font("宋体", Font.PLAIN, 20));
        acc.setBounds(200, 200, 300, 50);
        this.add(acc);


        saveText.setBounds(400, 200, 300, 50);
        saveText.setFont(new Font("宋体", Font.PLAIN, 20));
        this.add(saveText);


        imageBtn1.setBounds(650, 430, 140, 50);
        this.add(imageBtn1);
        imageBtn1.addActionListener(this);
        imageBtn2.setBounds(300, 430, 140, 50);
        this.add(imageBtn2);
        imageBtn2.addActionListener(this);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == imageBtn1) {
            frame.switchPanel("menu");
        } else if (e.getSource() == imageBtn2) {
            if (!saveText.getText().matches("^[0-9]+(.[0-9]{1,2})?$")){
                JOptionPane.showMessageDialog(this, "错误代码");
                return;
            }
            Double m = Double.parseDouble(saveText.getText()) + frame.getUsers().get(frame.getIndex()).getBalance();
            frame.getUsers().get(frame.getIndex()).setBalance(m);
            Util.writeObject("d:/users.bat",frame.getUsers());
            JOptionPane.showMessageDialog(this, "存款成功");
            saveText.setText("");

        }
    }
}
